import 'dart:developer';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/home/new_post_logic.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/widgets/picture_preview_widget.dart';
import 'package:ball_lion/widgets/select_bottomsheet.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

class NewPostPage extends StatefulWidget {
  const NewPostPage({super.key});

  @override
  State<NewPostPage> createState() => _NewPostPageState();
}

class _NewPostPageState extends State<NewPostPage> {
  final logic = Get.put(NewPostLogic());

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (logic.text.isNotEmpty) {
          final result =
              await Get.dialog(QsDialog.alert('关闭页面会清空已输入内容，是否继续退出？'));
          if (result == true) {
            return true;
          } else {
            return false;
          }
        } else {
          return true;
        }
      },
      child: Scaffold(
        appBar: Styles.appBar(
            title: QsText('发帖子'),
            onTapLeading: logic.onBack,
            actions: [
              GestureDetector(
                onTap: () {
                  if (logic.text.hasValue) logic.onSubmit();
                },
                child: Container(
                  margin: EdgeInsets.fromLTRB(0, 10, 16, 10),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Colours.main
                          .withOpacity(logic.text.hasValue ? 1 : 0.5),
                      borderRadius: BorderRadius.all(Radius.circular(4))),
                  width: 56,
                  height: 24,
                  child: QsText(
                    '发布',
                    color: Colours.white,
                    fontSize: 13,
                  ),
                ),
              )
            ]),
        body: GetBuilder<NewPostLogic>(
          builder: (_) {
            return GestureDetector(
              onTap: () {
                FocusScope.of(context).requestFocus(FocusNode());
              },
              child: ListView(children: [
                TextField(
                  controller: logic.textController,
                  // maxLength: 10,
                  // inputFormatters: [
                  //   LengthLimitingTextInputFormatter(10),
                  // ],
                  decoration: const InputDecoration(
                    fillColor: Colours.white,
                    filled: true,
                    border: OutlineInputBorder(borderSide: BorderSide.none),
                    hintText: '说点什么~',
                    contentPadding: EdgeInsets.all(16),
                    hintStyle: TextStyle(
                      color: Colours.grey99,
                      fontSize: 16,
                      fontWeight: FontWeight.w300,
                    ),
                  ),
                  style: TextStyle(fontSize: 16, color: Colours.text),
                  maxLines: 7,
                  keyboardType: TextInputType.multiline,
                  textInputAction: TextInputAction.newline,
                  // obscuringCharact
                  onChanged: (value) {
                    if (value.length > 3000) {
                      Toast.text('录入内容字数已达上限');
                      logic.textController.value = TextEditingValue(
                          text: logic.text,
                          selection: TextSelection.fromPosition(TextPosition(
                              affinity: TextAffinity.downstream,
                              offset: logic.text.length)));
                      // update();
                      return;
                    }
                    logic.text = value;
                    update();
                    // log(value);
                  },
                  onSubmitted: (value) {
                    log(value);
                  },
                ),
                SizedBox(height: 20),
                images()
              ]),
            );
          },
        ),
      ),
    );
  }

  images() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: GridView.builder(
        itemCount:
            logic.imageList.length + 1 > 9 ? 9 : logic.imageList.length + 1,
        padding: const EdgeInsets.only(bottom: 0),
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3, crossAxisSpacing: 6, mainAxisSpacing: 6),
        itemBuilder: (context, index) {
          if (index == logic.imageList.length) {
            return GestureDetector(
              onTap: () async {
                FocusScope.of(context).requestFocus(FocusNode());
                final result =
                    await Get.bottomSheet(SelectBottomSheet(['拍照', '从手机相册选择']));
                if (result == 0) {
                  logic.addPhotoFromCamera();
                } else if (result == 1) {
                  logic.addPhotoFromGallary();
                }
              },
              child: Image.asset(Utils.getImgPath('add_photo2.png')),
            );
          } else {
            return GestureDetector(
              onTap: () async {
                Get.dialog(PicturePreview(imageUrl: logic.imageList[index]),
                    useSafeArea: false);
              },
              child: Container(
                clipBehavior: Clip.antiAlias,
                decoration:
                    BoxDecoration(borderRadius: BorderRadius.circular(4)),
                child: Stack(
                  fit: StackFit.expand,
                  children: [
                    CachedNetworkImage(
                      imageUrl: logic.imageList[index],
                      fit: BoxFit.cover,
                      // width: double.infinity,
                      // height: 121,
                    ),
                    // Image.asset(
                    //   controller.otherImage[index],
                    //   fit: BoxFit.cover,
                    // ),
                    Positioned(
                        top: 0,
                        right: 0,
                        child: GestureDetector(
                          onTap: () {
                            logic.onDeleteImage(index);
                          },
                          child: Image.asset(
                            Utils.getImgPath('delete_image.png'),
                            width: 22,
                          ),
                        ))
                  ],
                ),
              ),
            );
          }
        },
      ),
    );
  }
}
